package com.yzh.openai.trigger.http;

import com.yzh.openai.domain.weixin.model.entity.MessageTextEntity;
import com.yzh.openai.domain.weixin.model.entity.UserBehaviorMessageEntity;
import com.yzh.openai.domain.weixin.service.IWeiXinBehaviorService;
import com.yzh.openai.domain.weixin.service.IWeiXinValidateService;
import com.yzh.openai.types.utils.xml.XmlUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 微信公众号控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/${app.config.api-version}/wx/")
public class WeiXinPortalController {

    @Resource
    private IWeiXinValidateService weiXinValidateService;
    @Resource
    private IWeiXinBehaviorService weiXinBehaviorService;   

    /**
     * 处理微信服务器发来的get请求，验签
     *
     * @param signature 签名
     * @param timestamp 时间戳
     * @param nonce     随机字符
     * @param echostr   验证字符
     * @return
     */
    @GetMapping
    public String validate(@RequestParam(value = "signature", required = false) String signature,
                           @RequestParam(value = "timestamp", required = false) String timestamp,
                           @RequestParam(value = "nonce", required = false) String nonce,
                           @RequestParam(value = "echostr", required = false) String echostr) {
        try {
            log.info("微信公众号验签开始 [signature：{}, timestamp：{}, nonce：{}, echostr：{}]", signature, timestamp, nonce, echostr);
            if (StringUtils.isAnyBlank(signature, timestamp, nonce, echostr)) {
                throw new IllegalArgumentException("微信公众号验签请求参数非法");
            }
            boolean check = weiXinValidateService.checkSign(signature, timestamp, nonce);
            if (!check) {
                throw new RuntimeException("微信公众号验签失败，系统异常");
            }
            log.info("微信公众号验签成功 [signature：{}, timestamp：{}, nonce：{}, echostr：{}]", signature, timestamp, nonce, echostr);
            return echostr;
        } catch (Exception e) {
            log.error("微信公众号验签失败 [signature：{}, timestamp：{}, nonce：{}, echostr：{}]", signature, timestamp, nonce, echostr, e);
            return null;
        }
    }

    /**
     * 接收微信转发的POST请求
     *
     * @param requestBody 请求体，也就是微信的xml信息
     * @param openid      发送信息用户的id
     * @return
     */
    @PostMapping
    public String post(@RequestBody String requestBody, @RequestParam("openid") String openid) {
        try {
            log.info("接收微信公众号信息请求{}开始\n{}", openid, requestBody);
            // 消息转换
            MessageTextEntity message = XmlUtil.xmlToBean(requestBody, MessageTextEntity.class);

            // 构建实体
            UserBehaviorMessageEntity entity = UserBehaviorMessageEntity.builder()
                    .openId(openid)
                    .fromUserName(message.getFromUserName())
                    .msgType(message.getMsgType())
                    .content(StringUtils.isBlank(message.getContent()) ? null : message.getContent().trim())
                    .createTime(new Date(Long.parseLong(message.getCreateTime()) * 1000L))
                    .event(message.getEvent())
                    .build();

            // 受理消息
            String result = weiXinBehaviorService.acceptUserBehavior(entity);
            log.info("接收微信公众号信息请求{}完成\n {}", openid, result);
            return result;
        } catch (Exception e) {
            log.error("接收微信公众号信息请求{}失败 {}", openid, requestBody, e);
            return "";
        }
    }
}
